package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.*;


/**
 * Servlet implementation class ProcessSPARQLRequest
 */
@WebServlet("/ProcessSPARQLRequest")
public class ProcessSPARQLRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessSPARQLRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String queryString = request.getParameter("query");
		process(queryString,response.getWriter());
	}
	
	public static void process(String queryString, PrintWriter writer){
		System.out.println("IN HANDLER");
		
		System.out.println("QUERY = " + queryString);

		Query query = QueryFactory.create(queryString);
		QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:2020/sparql", query);
	
		try {
			com.hp.hpl.jena.query.ResultSet results = qexec.execSelect();
			String output = "<table style=\"text-align: left; width: 100%;\"border=\"1\" cellpadding=\"2\" cellspacing=\"2\"><tbody>";
			
		    while(results.hasNext()){
		    	output += "<tr>";
		    
		    	QuerySolution qs = results.next();
		    	Iterator<String> it = qs.varNames();
		    	while(it.hasNext()){
		    		output+="<td><b>";
		    		String var = it.next();
		    		output += var + "</b></p>";
		    		RDFNode val = qs.get(var);
		    		if(val.isResource())
		    			output += qs.get(var).asResource().getURI();
		    		else if(val.isLiteral())
		    			output += qs.get(var).asLiteral().getString();
		    		output += "</td>";
		    	}
		    	output += "</td>";
		    }
		    output += "</tbody></table>";
		    System.out.println(output);
		    writer.write(output);
		    writer.close();
		    qexec.close();
		    
		}catch(Exception e){
			System.out.println(e);
		}
	}

}
